<template>
  <el-form :model="commentsFrom" ref="commentsFromRef" :rules="commentsRules">
    <el-form-item prop="text">
      <el-input type="textarea"
                maxlength="100"
                minlength="2"
                show-word-limit
                :placeholder="props.placeholder"
                :rows="5"
                v-model="commentsFrom.text"
      />
    </el-form-item>
    <el-form-item v-if="showSubmit">
      <el-button type="primary" @click="commentsFormSubmit(commentsFromRef)">发表评论</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import {FormInstance, FormRules} from "element-plus";
import {Response} from "~/entity/response";

const props = defineProps({
  siteId: {
    type: String,
    default: null
  },
  showSubmit: {
    type: Boolean,
    default: true
  },
  placeholder: {
    type: String,
    default: "请输入评论内容"
  }
});
const emit = defineEmits(["commentAfter", "commentBefore"]);
const {commentsApi} = useApi();
const {ModalUtils} = useUtils();
const id = ref(props.siteId);
const commentsFrom = reactive({
  text: ""
});
const commentsFromRef = ref<FormInstance>();
const commentsRules = reactive<FormRules>({
  text: [
    {required: true, message: '请填写评论内容', trigger: 'blur'},
  ]
});
const repliedUserName = ref("");
const commentsId = ref("");
const commentsFormSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    emit("commentBefore", valid);
    if (valid) {
      commentsApi.setComments(id.value, commentsFrom.text, repliedUserName.value, commentsId.value).then((res: any) => {
        const {data}: Response = res;
        if (data) {
          emit("commentAfter");
          commentsFrom.text = "";
          ModalUtils.msgSuccess("评论成功");
        }
      });
    } else {
      ModalUtils.msgWarning("请填写评论内容");
    }
  })
};
const updateRepliedUserName = (username: string) => {
  repliedUserName.value = username;
};
const updateCommentsId = (id: string) => {
  commentsId.value = id;
};
defineExpose({
  commentsFromRef,
  commentsFormSubmit,
  updateRepliedUserName,
  updateCommentsId
});
</script>

<style scoped lang="scss">
</style>